<template>
  <div class="goods">
    <!--左侧商品栏目区域-->
    <div class="menu-wrapper" ref='menuwrapper'>
      <ul>
        <li class="menu-item border-bottom" 
            v-for='(item,index) in this.goods' 
            :key='index'
            :class="{'current':currentIndex===index}"
             @click="selectMenu(index,$event)"
        >
          <div class='menu-item-center'>
            <span  class="icon" :class="classMap[item.type]" v-show="item.type>0"></span>
            <span class="text">{{item.name}}</span>
          </div>
        </li>
      </ul>
    </div>
    <!--右侧具体商品-->
    <div class="foods-wrapper" ref='foodswrapper'>
      <ul>
        <li class="food-list food-list-hook" 
            v-for="(item,index) in this.goods" 
            :key='index'    
        >
          <!--大标题，和左侧分类一致--->
          <h1 class="title">{{item.name}}</h1>
          <!--每个标题列表下的商品列表-->
          <ul>
            <li 
                class="food-item border-bottom" 
                v-for="(food,index) in item.foods" 
                :key='index'
                @click='selectFood(food,$event)'
            >
             <!--左侧图片-->
             <div class="icon">
               <img width="57" height="57" :src="food.icon" alt="food.name">
             </div>
             <!--右侧内容-->
             <div class="content">
                <h2 class="name">{{food.name}}</h2>
                <p class="desc">{{food.description}}</p>
                <div class="extra">
                  <span class="count">月售{{food.sellCount}}</span><span>好评率{{food.rating}}</span>
                </div>
                <!--现价与原价--->
                <div class="price">
                  <span class="now">￥{{food.price}}</span>
                  <span class="old" v-show="food.oldPrice" >￥{{food.oldPrice}}</span>
                </div>
                <!--商品添加组件------cartcontrol-wrapper起到定位的作用--->
                <div class="cartcontrol-wrapper">
                  <!--点菜按钮区域-->
                  <cartcontrol :food="food"></cartcontrol>
                </div>
             </div>
            </li>
          </ul>
        </li>
      </ul>
    </div>
    <shopcart :deliveryPrice="seller.deliveryPrice"
              :minPrice="seller.minPrice"
              :selectfoods="selectedfoods"
    >
    </shopcart>
  <food :food='selectFoodDetail' ref='fooddetailshow'></food>
  </div>
</template>

<script>
import axios from 'axios'
import BScroll from 'better-scroll' 
import shopcart from '../shopcart/shopcart'
import cartcontrol from '../cartcontrol/cartcontrol'
import food from '../food/food'

export default {
  name:'goods',
  props:{
    seller:Object
  },
  components:{
    shopcart,
    cartcontrol,
    food
  },
  data(){
    return{
      goods:[],
      listHeight:[],//存储不同区域的高度
      scrollY: 0,
      selectFoodDetail:{}//存储点击的商品项，显示该商品的详情页
    }
  },
  computed:{
    currentIndex() {
      for (let i = 0; i < this.listHeight.length; i++) {
        let height1 = this.listHeight[i];
        let height2 = this.listHeight[i + 1];
        if (!height2 || (this.scrollY >= height1 && this.scrollY < height2)) {
          return i;
        }
      }
      return 0;
    },
    //selectFoods函数返回一个数组，每个数组项包含商品单价与选择的数量
    selectedfoods(){
      let foods=[];
      //遍历所有类的商品
      this.goods.forEach((good)=>{
        //遍历每一类的所有的商品，此处使用good.foods，千万不要用this.good，good代表形参，不需要this指向实例自身
        good.foods.forEach((food)=>{
          //如果某一个商品被选中，则其通过cartcontrol组件vue.set添加过count属性
          if(food.count){
            foods.push(food)
          }
        })
      })
      return foods;
    }
  },
  methods:{
    //点击的食品项，会显示食品页面详情
    selectFood(food,event){
      //浏览器原生的事件不包含_constructed属性，scroll派发的点击事件包含，并且为true
      if (!event._constructed) {
        return;//浏览器原生点击事件被阻止，只有当scroll事件派发的点击才执行接下去的操作
      }
      this.selectFoodDetail=food;
      this.$refs.fooddetailshow.show();
    },
    _initScroll(){
      this.menuscroll = new BScroll(this.$refs.menuwrapper,{
        click:true//阻止浏览器默认事件
      })//利用$refs来操作dom
      this.foodscroll = new BScroll(this.$refs.foodswrapper,{
        click:true,//阻止浏览器默认事件
        probeType: 3//当 probeType 为 3 的时候，不仅在屏幕滑动的过程中，而且在 momentum 滚动动画运行过程中实时派发 scroll 事件
      })//利用$refs来操作dom
       this.foodscroll.on('scroll',(pos)=>{
          this.scrollY = Math.abs(Math.round(pos.y));//实时的Y坐标，绝对值，转整数
       })
    },
    _calculateHeight(){
     //拿到食品列表中的每个元素li
      let height = 0;
      this.listHeight.push(height);
      let foodList=document.getElementsByClassName('food-list-hook')
      setTimeout(()=>{
        for (let i = 0; i < foodList.length; i++) {
          let item = foodList[i];
          height += item.clientHeight;
          this.listHeight.push(height);
        }
        //console.log(foodList.length)
        //console.log(foodList)
        //console.log(this.listHeight)
      },20)
    },
     /*let foodList=document.getElementsByClassName('food-list-hook')
      let height = 0;
      this.listHeight.push(height);
      this.$nextTick(
        ()=>{
           for (let i = 0; i < foodList.length; i++) {
          let item = foodList[i];
          height += item.clientHeight;
          this.listHeight.push(height);
        }
        console.log(foodList.length)//0
        console.log(foodList)//为空
        console.log(this.listHeight)//空数组
        }
      )
     
    },*/

    selectMenu(index,event) {
      //浏览器原生的事件不包含_constructed属性，scroll派发的点击事件包含，并且为true
      if (!event._constructed) {
        return;//浏览器原生点击事件被阻止，只有当scroll事件派发的点击才执行接下去的操作
      }
      let foodList=document.getElementsByClassName('food-list-hook')
      let el = foodList[index]
      this.foodscroll.scrollToElement(el, 300);
    },
    /*setTimeout(()=>{
      console.log('-￥￥￥￥￥￥￥￥￥￥￥￥-延时器')
      console.log(foodList.length)
      console.log(foodList[3])
      let height = 0;
      this.listHeight.push(height);
      for (let i = 0; i < foodList.length; i++) {
        let item = foodList[i];
        height += item.clientHeight;
        this.listHeight.push(height);
        }
      console.log(this.listHeight)
      console.log('---￥￥￥￥￥---延时器')
    },20)
    console.log('------开始-----------无延时器')
    console.log(foodList)
    console.log(foodList[3])
    console.log('--------结束---------无延时器')
    }*/
   //获取ajax返回的数据
    change(res){
      const data=res.data
      this.goods=data.goods
    },
},
/* watch:{
      goods(){
         this._initScroll();
      }
  },*/
 created(){
    this.classMap = ['decrease', 'discount', 'special', 'invoice', 'guarantee'];
    axios.get('/api/data.json')
      .then(this.change)
    this.$nextTick(() => {
      this._initScroll();
       this._calculateHeight();
     });
  }
}
</script>

<style lang="stylus" scoped>
@import "../../commen/stylus/mixin.styl"
.goods 
  //视口高度
  display: flex
  position: absolute
  top:176px
  bottom:46px
  overflow: hidden
  width:100%
  .menu-wrapper
    flex: 0 0 80px
    width: 80px
    background:#f3f5f7
    .menu-item
      display:table
      height:54px 
      width:56px 
      line-height:14px
      padding:0 12px//(80-56)/2
      &.border-bottom:before
        border-color:rgba(7, 17, 27, 0.1)
      &.current
        position: relative
        z-index: 10px
        margin-top: -1px
        background: #ffffff
        font-weight: 800
      .menu-item-center
        width:54px 
        display:table-cell
        vertical-align:middle//竖直居中
        .icon
          display: inline-block
          width: 12px
          height: 12px
          vertical-align:bottom
          margin-right: 2px
          background-size: 12px 12px
          background-repeat: no-repeat
          &.decrease
            bg-image('decrease_3')
          &.discount
            bg-image('discount_3')
          &.guarantee
            bg-image('guarantee_3')
          &.invoice
            bg-image('invoice_3')
          &.special
            bg-image('special_3')
        .text
          font-size: 12px
  .foods-wrapper
    flex:1
    .title
      padding-left: 14px
      height: 26px
      line-height: 26px
      border-left: 2px solid #d9dde1
      font-size: 12px
      color: rgb(147, 153, 159)
      background: #f3f5f7
    .food-item
      display:flex
      margin: 18px
      padding-bottom: 18px//应对上下边距合并
      //每个列表的最后一项没有分割线
      &:last-child.border-bottom:before 
        display:none
      &:last-child.border-bottom
        margin-bottom: 0//应对最后一个列表项既有margin又有padding-bottom项，两倍间距
      .icon
        flex: 0 0 57px
        margin-right: 10px 
      .content
        flex:1
        .name 
          margin: 2px 0 8px 0
          height: 14px
          line-height: 14px
          font-size: 14px
          color: rgb(7, 17, 27)
        .desc,.extra
          line-height: 10px
          font-size: 10px
          color: rgb(147, 153, 159)
        .desc
          line-height: 12px
          margin-bottom: 8px
        .extra
          line-height: 10px
          .count 
            margin-right:12px
        .price 
          font-weight: 700
          line-height: 24px 
          .now 
            font-size: 14px
            color: rgb(240, 20, 20) 
          .old
            text-decoration: line-through
            color: rgb(147, 153, 159)
            font-size: 10px  
        .cartcontrol-wrapper
          position:absolute
          right:0 
          bottom:12px
</style>